<template>
  <!-- 班组人员管理 -->
  <base-breadcrumb>
    <!-- 基础信息 -->
    <a-spin :spinning="loading">
      <a-card :bordered="false">
        <title-name title="基础信息"></title-name>
        <custom-form :formList="projectForm" isValidate :form="form" editModel="V"></custom-form>
      </a-card>
      <!-- 管理岗 -->
      <a-card :bordered="false">
        <title-name title="班组人员列表"></title-name>
        <a-row type="flex" class="mb12">
          <a-button class="mr20" type="primary" icon="plus" @click="handleManage(0, 0)">添加人员</a-button>
          <!-- <a-button class="mr20" type="primary" icon="import" @click="handleManage(1, 0)">批量导入</a-button>
          <a-button type="primary" icon="download" @click="handleManage(0, 0)">导入模板下载</a-button> -->
        </a-row>
        <s-table
          bordered
          ref="table"
          size="default"
          rowKey="id"
          :columns="columns"
          :data="loadData"
          :showPagination="false"
        >
          <template v-if="record.statusCode == 1 && record.duty == 2" slot="actions" slot-scope="text, record">
            <a @click="handleManage(0, 1, record)">修改</a>
          </template>
          <template slot="view" slot-scope="text, record">
            <a @click="handleMove(record)">查看完整信息</a>
          </template>
        </s-table>
      </a-card>
    </a-spin>
    <!-- 页脚操作栏 -->
    <div
      class="btn_box page-btn-right-top"
      style="position: fixed; bottom: 0; right: 50px; height: 50px; display: flex; align-items: center; z-index: 99"
    >
      <!-- <a-button type="primary" @click="handleConfirm" class="mr20">提交</a-button> -->
      <a-button type="primary" @click="close">关闭</a-button>
    </div>
    <!-- 表单弹窗 -->
    <dialog-form
      ref="dialogForm"
      :visible.sync="visible"
      editModel="E"
      :form="forms"
      :forms.sync="forms"
      :headerTitle="[`人员${['添加', '修改'][editModel]}`, '班组设置', '班组长设置'][dialogType]"
      :width="1000"
      :formList="[manageForm, importForm][dialogType]"
      :rules="rules"
      @confirm="handleConfirm"
      @search="handleSearch"
    >
      <!-- 附件上传 -->
      <template #fileArrays>
        <l-table businessCode="QM04" :uploadArrys.sync="form.fileArrays"></l-table>
      </template>
    </dialog-form>
  </base-breadcrumb>
</template>

<script>
import { STable, Ellipsis } from '@/components'
import BaseEditPage from '@/views/baseEditPage' // 编辑详情页基础配置
import DialogForm from '@/components/DialogForm' // 表单弹窗
import { createValidator, idCard, isPhone, isName } from '@/utils/regExpression' // 正则校验
import { getPersonList, getSubTeam, addSubTeamMem, editSubTeamMem } from '@/api/project/projects'
import SelectJobs from '@/components/Select/SelectJobs' // 表单弹窗
import Selector from '@/components/Select/Selector' // 表单弹窗

const columns = [
  {
    title: '序号',
    dataIndex: 'index',
    width: 100,
    customRender() {
      return arguments[2] + 1
    },
  },
  {
    title: '姓名',
    dataIndex: 'name',
    ellipsis: true,
  },
  {
    title: '联系电话',
    dataIndex: 'phone',
    ellipsis: true,
  },

  {
    title: '身份证号码',
    width: 230,
    dataIndex: 'idCard',
  },
  {
    title: '性别',
    width: 100,
    dataIndex: 'sexName',
  },
  {
    title: '工种',
    dataIndex: 'workTypeName',
    ellipsis: true,
    customRender(){
      return arguments[0] || '无'
    }
  },
  {
    title: '岗位',
    dataIndex: 'postName',
    ellipsis: true,
  },
  {
    title: '状态',
    width: 100,
    dataIndex: 'statusName',
  },
  {
    title: '操作',
    dataIndex: 'actions',
    width: 150,
    scopedSlots: { customRender: 'actions' },
  },
  {
    title: '查看',
    dataIndex: 'view',
    width: 150,
    scopedSlots: { customRender: 'view' },
  },
]

export default {
  extends: new BaseEditPage(),
  name: 'groupEmployeeManage',
  components: {
    STable,
    Ellipsis,
    DialogForm,
  },
  data() {
    return {
      columns, // 管理岗表头
      searchLoading: false, // 身份证搜索loading
      loading: false, // 页面loading
      form: {}, // 表单
      forms: {}, // 弹窗表单
      dialogType: 0, // 弹窗类型：0 管理人员；1 人员信息批量导入
      editModel: 0, // 弹窗操作类型：0 添加；1 编辑
      visible: false, // 弹窗显隐控件
      isExist: false, // 身份证人员是否已存在
      list: [], // 表格
      loadData: () => {
        return new Promise((resolve) => {
          resolve({
            data: this.list,
          })
        })
      }, // 班组表格
      rules: {
        idCard: [
          { required: true, validator: createValidator(idCard, '请输入正确的身份证号码', true), trigger: 'blur' },
        ],
        name: [{ required: true, whitespace: true, message: '请输入正确的姓名', trigger: 'change' }],
        // name: [{ required: true, validator: createValidator(isName, '请输入正确的姓名', true), trigger: 'change' }],
        sex: [{ required: true, message: '请选择性别', trigger: 'change' }],
        phone: [{ required: true, validator: createValidator(isPhone, '请输入正确的手机号码', true), trigger: 'blur' }],
        postName: [{ required: true, message: '请选择岗位', trigger: 'change' }],
        workTypeName: [{ required: true, message: '请选择工种', trigger: 'change' }],
        statusCode: [{ required: true, message: '请选择当前状态', trigger: 'change' }],
        enterDate: [{ required: true, message: '请选择进场时间', trigger: 'change' }],
        exitDate: [{ required: true, message: '请输入出场时间', trigger: 'change' }],
        fileArrays: [{ type: 'array', required: true, message: '请上传文件', trigger: 'blur' }],
      }, // 表单校验
    }
  },
  computed: {
    // 基础信息表单列表
    projectForm() {
      return [
        {
          keyName: 'branchCompanyName',
          label: '分公司',
        },
        {
          keyName: 'projectName',
          label: '项目',
        },
        {
          keyName: 'subContractorName',
          label: '分包',
        },
        {
          keyName: 'teamName',
          label: '班组名称',
        },
        {
          keyName: 'enterDate',
          label: '进场时间',
        },
        {
          keyName: 'statusName',
          label: '当前状态',
        },
        {
          keyName: 'exitDate',
          label: '出场时间',
          hidden: this.form.statusCode == 1,
        },
      ]
    },
    // 管理人员表单列表
    manageForm() {
      return [
        {
          keyName: 'idCard',
          type: 'a-input-search',
          label: '身份证号码',
          disabled: this.editModel == 1,
          span: 12,
          attrs: {
            loading: this.searchLoading,
          },
        },
        {
          keyName: 'name',
          type: 'BaseInput',
          disabled: this.isExist || this.editModel == 1,
          label: '姓名',
          span: 12,
        },
        {
          keyName: 'sex',
          type: 'a-select',
          disabled: this.isExist || this.editModel == 1,
          label: '性别',
          span: 12,
          data: [
            {
              value: '0',
              label: '女',
            },
            {
              value: '1',
              label: '男',
            },
          ],
        },
        {
          keyName: 'phone',
          type: 'BaseInput',
          label: '手机号码',
          span: 12,
        },
        {
          keyName: 'postName',
          label: '岗位',
          span: 12,
          disabled: true,
          type: 'BaseInput',
          // attrs: {
          //   attr: {
          //     rootOrgId: this.projectOrgId,
          //   },
          // },
        },
        {
          type: Selector,
          keyName: 'workTypeName',
          label: '工种',
          span: 12,
          attrs: {
            selectType: '37',
            urlType: 'project',
            attr: { statusCode: '1' },
            valueName: 'name',
          },
        },
        {
          keyName: 'statusCode',
          type: 'a-select',
          disabled: this.editModel == 0,
          label: '当前状态',
          data: [
            {
              label: '出场',
              value: '0',
            },
            {
              label: '进场',
              value: '1',
            },
          ],
          span: 12,
        },
        {
          keyName: 'enterDate',
          type: 'a-date-picker',
          label: '进场时间',
          span: 12,
          attrs: {
            valueFormat: 'YYYY-MM-DD',
            disabledDate: (current) => {
              // Can not select days before today and today
              return (
                (this.forms.exitDate && current && current > this.moment(this.forms.exitDate).startOf('day')) ||
                (this.form.enterDate && current && current < this.moment(this.form.enterDate).startOf('day'))
              )
            },
          },
        },
        {
          keyName: 'exitDate',
          type: 'a-date-picker',
          hidden: this.forms.statusCode == 1,
          label: '出场时间',
          span: 12,
          attrs: {
            valueFormat: 'YYYY-MM-DD',
            disabledDate: (current) => {
              // Can not select days before today and today
              return this.forms.enterDate && current && current < this.moment(this.forms.enterDate).endOf('day')
            },
          },
        },
      ]
    },
    // 导入表单列表
    importForm() {
      return [
        {
          keyName: 'postName',
          type: SelectJobs,
          label: '岗位',
          span: 12,
          attrs: {
            attr: {
              rootOrgId: this.projectOrgId,
            },
          },
        },
        {
          type: Selector,
          keyName: 'projectType',
          label: '工种',
          span: 12,
          attrs: {
            selectType: '37',
            urlType: 'project',
            labelInValue: true,
            attr: { statusCode: '1' },
          },
        },
        {
          slot: true,
          keyName: 'fileArrays',
          label: '文件选择',
          span: 24,
        },
      ]
    },
  },
  mounted() {
    // 设置基础信息
    this.loading = true
    this.init()
      .then((res) => {
        this.loading = false
        if (res.data) {
          this.form = res.data
          this.list = res.data.teamMembers
          this.$refs.table.refresh(true)
        }
      })
      .catch(() => {
        this.loading = false
      })
  },
  methods: {
    /**
     * 关闭‘
     */
    close() {
      window.close()
    },
    /**
     * 初始化
     */
    init() {
      return getSubTeam({ id: this.id })
    },
    /**
     * 获取列表
     */
    getlist() {
      this.$refs.table.localLoading = true
      this.init()
        .then((res) => {
          this.$refs.table.localLoading = false
          if (res.data) {
            this.list = res.data.teamMembers
            this.$refs.table.refresh(true)
          }
        })
        .catch(() => {
          this.$refs.table.localLoading = false
        })
    },
    /**
     * 添加或编辑操作；dialogType弹窗类型：0 班组管理人员；1 导入人员；type操作类型：type: 0 添加，1 编辑；record：编辑项
     */
    handleManage(dialogType, type, record) {
      this.dialogType = dialogType
      this.editModel = type
      this.forms = record || { statusCode: '1',enterDate:this.moment().format("YYYY-MM-DD") }
      this.forms.teamId = this.id
      if (!this.forms.postName) {
        this.forms.postName = '作业人员'
      }
      this.visible = true
    },
    /**
     * 根据身份证搜索人员
     */
    handleSearch() {
      let value = arguments[1] // 搜索值
      this.searchLoading = true
      this.$refs.dialogForm.$refs.ruleForm.validateField('idCard', (valid) => {
        if (!valid) {
          getPersonList({ idCard: value })
            .then((res) => {
              this.searchLoading = false
              if (res.data?.length > 0) {
                let datas = res.data[0]
                this.$set(this.$refs.dialogForm.forms, 'name', datas.name)
                this.$set(this.$refs.dialogForm.forms, 'sex', datas.sex)
                this.$set(this.$refs.dialogForm.forms, 'phone', datas.phone)
                this.$set(this.$refs.dialogForm.forms, 'laborerId', datas.id)
                this.isExist = true
                this.$message.success('获取人员信息成功！')
              } else {
                this.$message.warning('人员基础库里无此人员！')
              }
            })
            .catch(() => {
              this.searchLoading = false
            })
        } else {
          this.searchLoading = false
        }
      })
    },
    /**
     * 提交表单
     */
    handleConfirm(e) {
      let api = [addSubTeamMem, editSubTeamMem][this.editModel]
      this.$refs.dialogForm.loading = true
      e.projectId = this.form.projectId
      e.inAndOutId = this.form.inAndOutId
      api(e)
        .then((res) => {
          this.$refs.dialogForm.loading = false
          if (res.data) {
            if (this.editModel == 0) {
              window.opener.location.reload()
            }
            this.$message.success(['添加', '修改'][this.editModel] + '成功！')
            this.visible = false
            this.getlist()
          }
        })
        .catch(() => {
          this.$refs.dialogForm.loading = false
        })
    },
    /**
     * 跳转人员详情
     */
    handleMove(e) {
      // window.open(`/baseSetting/personManageEdit?businessId=${e.laborerId}&editModel=0`)
      this.$router.push({
        path: '/baseSetting/personManageEdit',
        query: {
          id: e.laborerId,
          editModel: 0,
          isBack: 1,
        },
      })
    },
  },
  watch: {
    visible(e) {
      !e && (this.isExist = false)
    },
    'forms.idCard'(e) {
      this.$refs.dialogForm.forms.name && this.$set(this.$refs.dialogForm.forms, 'name', '')
      this.$refs.dialogForm.forms.sex && this.$set(this.$refs.dialogForm.forms, 'sex', void 0)
      this.$refs.dialogForm.forms.phone && this.$set(this.$refs.dialogForm.forms, 'phone', '')
      if (this.isExist) this.isExist = false
    },
  },
}
</script>
<style lang="less" scoped>
/deep/ .ant-input-search {
  input {
    cursor: default;
  }
}
/deep/.ant-input-number {
  border: none;
}
/deep/.ant-input-number-input {
  border: 1px solid #d9d9d9;
  border-radius: 4px;
}
/deep/ .ant-input:not([disabled]),
/deep/ .ant-select:not(.ant-select-disabled) .ant-select-selection,
/deep/ .ant-calendar-picker-input,
/deep/ .ant-input-number-input,
/deep/ .ant-cascader-picker {
  border-color: #e4ac0b;
  background-color: #fff9e8;
}
//输入框的禁用颜色，
//2020//11/30备注：去掉了.ant-calendar-picker-input,这个
/deep/ .ant-input-disabled,
/deep/ .ant-input-number-disabled .ant-input-number-input {
  border-color: #d9d9d9 !important;
  background-color: #f5f5f5 !important;
}
</style>